import { orderApiConfig, OrderData, Process, Source } from "@/api/order";
import { orderStore } from "@/db";
import { baseURL } from "@/request/config";
import { transform } from "lodash";
import Mock from "mockjs-async";
import qs from "qs";
import { mockInputData, mockLayoutData } from "../data";
import { taskData } from "../data/task-data";
import "./mock-fix";

type ApiConfig = typeof orderApiConfig

function getMockApiConfig(apiConfig: ApiConfig, baseURL: string) {
  return transform<ApiConfig, ApiConfig>(apiConfig, (result, value, key) => {
    result[key] = { ...value, url: baseURL + value.url }
  })
}
function getQueryParams(url: string) {
  return qs.parse(url.split('?')[1])
}
function getData(options) {
  return JSON.parse(options.body)
}

const apiConfig = getMockApiConfig(orderApiConfig, baseURL)

const mockOrderData: OrderData = [
  {
    id: '1',
    date: 1653037557093,
    source: Source.Import,
    process: Process.Wait,
    ratio: .1,
    count: 55,
    time: 60000,
    taskData
  },
  {
    id: '2',
    date: 1653037557093,
    source: Source.ThirdOrder,
    process: Process.Finish,
    ratio: .1,
    count: 55,
    time: 60000,
    taskData
  },
  {
    id: '3',
    date: 1653037557093,
    source: Source.CurrentDesign,
    process: Process.Finish,
    ratio: .1,
    count: 55,
    time: 60000,
    taskData
  },
]

const log = console.log.bind(console, '[mock]')

Mock.mock(apiConfig.add.url, (options) => {
  log("addOrder", options)
  const data = getData(options)
  return orderStore.add(data)
})
Mock.mock(apiConfig.del.url, (options) => {
  log('delOrder', options);
  const data = getData(options)
  const { id } = data
  return orderStore.del(id)
  // mockOrderData.splice(mockOrderData.findIndex(item => item.id === id), 1)
})
Mock.mock(apiConfig.update.url, (options) => {
  log("updateOrder", options);
  const data = getData(options)
  return orderStore.update(data)
})
Mock.mock(apiConfig.list.url, (options) => {
  return (async () => {
    log("listOrder", options);
    const list = await orderStore.list()
    // log(list);
    return list
    // return Promise.resolve([...mockOrderData])
  })()
  // }
})
Mock.mock(new RegExp(apiConfig.detail.url), (options) => {
  log("getOrder", options);
  const { url } = options
  const params = getQueryParams(url)
  // return { inputData: mockInputData, layoutDatas: [mockLayoutData] }
  const id = params.id as string
  return orderStore.get(id)
})